package com.qk.management.web.filter;

import cn.hutool.core.util.ObjectUtil;
import com.qk.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @description 登录校验过滤器
 */
@Slf4j
//@WebFilter("/*")
public class LoginCheckFilter implements Filter {
    private static final String LOGIN_PATH = "/login";
    private static final String TOKEN_HERDER_NAME  = "token";
    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        //1、将请求对象和响应对象强转成HttpServletRequest和HttpServletResponse
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;

        //2、获取请求路径
        String path = request.getRequestURI();
        log.info("------拦截到的请求路径是：{}------", path);

        //3、判断当前请求是否为登录请求
        boolean isLoginReq = ObjectUtil.equal(path, LOGIN_PATH);
        if(isLoginReq){
            //放行
            chain.doFilter(request, response);
            return;
        }

        //4、不是登录请求，获取请求头中的token
        String token = request.getHeader(TOKEN_HERDER_NAME);
        if(ObjectUtil.isEmpty( token)){
            response.setStatus(401);
            return;
        }

        //5、验证 token
        try{
            Claims claims = JwtUtils.parseToken(token);
            String username = claims.get("username", String.class);
            log.info("当前用户是：{}", username);
            Object id = claims.get("id");
            log.info("当前用户id是：{}", id);
            //放行
            chain.doFilter(request, response);
        }catch (Exception e){
            log.error("token验证失败：{}", e.getMessage());
            response.setStatus(401);
            return;
        }
    }
}
